package com.soft.javase.ch09.test.hashSet;

import java.util.HashSet;
import java.util.Set;

/**
 * @author wangzhisen
 * @Desc TODO
 * @date 2025/5/5
 */

class Main {
    public static void main(String[] args) {
        // 创建Person数组，包含重复对象
        Person[] persons = {
                new Person("张三", 25),
                new Person("李四", 30),
                new Person("张三", 25), // 重复
                new Person("王五", 28),
                new Person("李四", 30)  // 重复
        };

        System.out.println("原始数组:");
        for (Person p : persons) {
            System.out.println(p);
        }

        // 使用HashSet去除重复
        Set<Person> uniquePersons = new HashSet<>();
        for (Person p : persons) {
            uniquePersons.add(p);
        }

        System.out.println("\n去重后的结果:");
        for (Person p : uniquePersons) {
            System.out.println(p);
        }
    }
}

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Person person = (Person) obj;
        return age == person.age && name.equals(person.name);
    }

    @Override
    public int hashCode() {
        int result = name.hashCode();
        result = 31 * result + age;
        return result;
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }
}
